﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;

namespace twilters
{
    /// <summary>
    /// Interaction logic for FilterWindow.xaml
    /// </summary>
    public partial class FilterWindow : System.Windows.Window
    {
        private TwitterClient client;
        private DataStore dataStore;
        private MainWindow mainWindow;
        private Filter selectedFilter;
        private String fName;
        public FilterWindowModel presentationModel;


        private List<FilterLineItem> lineItems;

        private BackgroundWorker backgroundWorker;

        private delegate void NoArgDelegate();

        public FilterWindow(MainWindow mainWindow, TwitterClient client, DataStore dataStore, Filter selectedFilter)
        {
            InitializeComponent();
            InitializeBackgroundWorker();
            // Get a handle on the root window presentation model resource
            ObjectDataProvider odp = (ObjectDataProvider)filterWindow.Resources["presentationModel"];
            presentationModel = (FilterWindowModel)odp.ObjectInstance;

            this.mainWindow = mainWindow;
            this.client = client;
            this.dataStore = dataStore;
            this.selectedFilter = selectedFilter;
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            int index = GetListViewItemIndex(e.OriginalSource as DependencyObject);
            presentationModel.AddNewRow(index + 1);
        }

        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            ItemCollection items = lineItemListView.Items;
            if (items.Count == 1) { return; }

            int index = GetListViewItemIndex(e.OriginalSource as DependencyObject);
            presentationModel.RemoveRowFromCurrentFilterSheet(index);
        }

        private int GetListViewItemIndex(DependencyObject depObj)
        {
            while (!(depObj is ListViewItem))
            {
                depObj = VisualTreeHelper.GetParent(depObj);
            }

            return lineItemListView.ItemContainerGenerator.IndexFromContainer(depObj);
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            lineItems = new List<FilterLineItem>();
            foreach (FilterLineItem item in lineItemListView.Items)
            {
                FilterLineItem f = new FilterLineItem();
                f.MatchType = item.MatchType;
                f.Field = item.Field;
                f.Content = item.Content;
                lineItems.Add(f);
            }
           // NoArgDelegate fetcher = new NoArgDelegate(this.SaveFilter);
            //fetcher.BeginInvoke(null, null);
            fName = filterName.Text;
            saveButton.IsEnabled = false;
            cancelButton.IsEnabled = false;
            this.Cursor = Cursors.Wait;
            backgroundWorker.RunWorkerAsync();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            SaveFilter();
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
            saveButton.IsEnabled = true;
            cancelButton.IsEnabled = true;
            FinishFilterSave();
        }

        private void InitializeBackgroundWorker()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
        }

        private void SaveFilter()
        {
            try
            {
                Filter filter;
                if (selectedFilter != null)
                {
                    filter = selectedFilter;
                    filter.GetParameters().Clear();
                }
                else
                {
                    filter = new Filter(fName, dataStore.NextId());
                }
                filter.OwnerUsername = client.CurrentUserName();
                foreach (FilterLineItem item in lineItems)
                {
                    if (item.Field != null && item.Content.Trim().Length > 0 && item.MatchType != null)
                    {
                        filter.AddParameter(new FilterParameter(item.Field, item.Content, item.MatchType));
                    }
                }
                if (filter.GetParameters().Count > 0)
                {
                    dataStore.storeFilter(filter);
                }
            }
            catch (Exception exc)
            {
                WindowUtil.displayError(exc.Message);
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void FinishFilterSave()
        {
            mainWindow.Reload_Filters();
            Close();
        }

        private void filterWindow_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void filterName_TextChanged(object sender, RoutedEventArgs e)
        {
        }
    }
}
